package com.fagp.mew.cms.permission;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mew.common.dc.mapper.AdminMapper;
import com.mew.common.dc.mapper.PermissionMapper;
import com.mew.common.entity.back.Admin;
import com.mew.common.entity.back.Permission;
import com.fagp.mew.cms.vo.AdminVo;
import com.mew.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * 认证和授权
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //--------------------认证账号
        Admin admin = new Admin();
        admin.setUsername(s);
        admin.setState(1);
        LambdaQueryWrapper<Admin> adminwrapper = new LambdaQueryWrapper<>(admin);
        admin = adminMapper.selectOne(adminwrapper);
        if (admin == null) {
            throw new UsernameNotFoundException("账号不存在");
        }

        AdminVo adminVo = AdminVo.toVo(admin);
        //-------------------开始授权
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        ArrayList<Permission> preByName = permissionMapper.getByName(admin.getUsername());
        for (Permission permission : preByName) {
            if (null!=permission&& StringUtils.isNotEmpty(permission.getName())){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getType());
                //此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                grantedAuthorities.add(grantedAuthority);
            }
        }
        adminVo.setAuthorities(grantedAuthorities);

        return adminVo;
    }

}
